package com.xxxx.rpc.service.impl;

import com.xxxx.rpc.service.SearchService;
import com.xxxx.rpc.vo.GoodsVo;
import org.apache.dubbo.config.annotation.Service;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Desc
 * @Author lsh
 * @Create Time 2021/1/4 14:07
 */
@Service(interfaceClass = SearchService.class)
@Component
public class SearchServiceImpl implements SearchService{
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public List<GoodsVo> doSearch(String searchStr, Integer pageNum, Integer pageSize) {
        List<GoodsVo>goodsVoList = new ArrayList<>();
        try {
            SearchRequest searchRequest = new SearchRequest("shop");
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("goodsName").preTags("<span style='color:red'>").postTags("</span>");

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.from((pageNum-1)*pageSize).size(pageSize).highlighter(highlightBuilder);

            searchSourceBuilder.query(QueryBuilders.multiMatchQuery(searchStr,"goodsName"));
            searchRequest.source(searchSourceBuilder);

            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            long count = search.getHits().getTotalHits().value;
            if (count>0){
                SearchHit[] hits = search.getHits().getHits();
                for (SearchHit hit : hits) {
                    GoodsVo goodsVo = new GoodsVo();
                    goodsVo.setGoodsId((Integer)(hit.getSourceAsMap().get("goodsId")));
                    goodsVo.setGoodsName((String) hit.getSourceAsMap().get("goodsName"));
                    goodsVo.setGoodsNameHl(String.valueOf(hit.getHighlightFields().get("goodsName").getFragments()[0]));
                    goodsVo.setMarketPrice(new BigDecimal(String.valueOf(hit.getSourceAsMap().get("marketPrice"))));
                    //goodsVo.setMarketPrice(new BigDecimal("1.234"));
                    goodsVo.setOriginalImg((String)hit.getSourceAsMap().get("originalImg"));
                    goodsVoList.add(goodsVo);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return goodsVoList;

    }
}
